package com.cats.bi.sqltool.function;

import com.cats.bi.sqltool.SQLString;
import com.cats.bi.sqltool.basic.AbstractSearchable;
import com.cats.bi.sqltool.basic.Column;
import lombok.EqualsAndHashCode;

import java.util.LinkedList;

/**
 * @author wang jian
 * @Description
 * @create 2021/4/7
 */
@EqualsAndHashCode(callSuper = false)
public class Case extends Column {
    private Object other;
    private LinkedList<Object> kv = new LinkedList<>();

    public Case(String name) {
        this((String) null, name);
    }

    public Case(String table, String name) {
        super(table, name);
    }

    public Case(AbstractSearchable<?> table, String name) {
        super(table, null, name);
    }

    public Case when(Object when, Object then) {
        kv.addLast(when);
        kv.addLast(then);
        return this;
    }

    public Case elseAs(Object other) {
        this.other = other;
        return this;
    }

    @Override
    public void toSql(StringBuilder sb) {
        sb.append("CASE ");
        super.toSql(sb);
        for (Object object : kv) {
            sb.append(" WHEN ");
            SQLString.appendValue(sb, object);
        }
        if (other != null) {
            sb.append(" ELSE ");
            SQLString.appendValue(sb, other);
        }
        sb.append(" END");
    }

}
